import React, { useState, useContext, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { FaGithub, FaGoogle } from 'react-icons/fa';
import { AuthContext } from '../contexts/AuthContext';

const Register = () => {
  const { register: registerUser, isAuthenticated, error: authError } = useContext(AuthContext);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [registerError, setRegisterError] = useState(null);
  const [registerSuccess, setRegisterSuccess] = useState(false);
  const navigate = useNavigate();
  
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm();
  
  // 监听密码字段，用于确认密码验证
  const password = watch('password', '');
  
  useEffect(() => {
    // 如果已经登录，重定向到首页
    if (isAuthenticated) {
      navigate('/');
    }
  }, [isAuthenticated, navigate]);
  
  useEffect(() => {
    if (authError) {
      setRegisterError(authError);
    }
  }, [authError]);
  
  const onSubmit = async (data) => {
    setIsSubmitting(true);
    setRegisterError(null);
    
    try {
      const success = await registerUser(data.username, data.email, data.password);
      if (success) {
        setRegisterSuccess(true);
        setTimeout(() => {
          navigate('/login');
        }, 3000);
      }
    } catch (err) {
      setRegisterError('注册失败，请稍后再试');
    } finally {
      setIsSubmitting(false);
    }
  };
  
  return (
    <div className="flex justify-center items-center py-12">
      <div className="max-w-md w-full space-y-8 card p-8">
        <div className="text-center">
          <h2 className="text-3xl font-extrabold text-dark-800 dark:text-dark-200">
            注册账号
          </h2>
          <p className="mt-2 text-sm text-dark-500 dark:text-dark-400">
            或{' '}
            <Link to="/login" className="text-primary-600 dark:text-primary-400 hover:underline">
              登录已有账号
            </Link>
          </p>
        </div>
        
        {registerError && (
          <div className="bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-200 p-3 rounded-md text-sm">
            {registerError}
          </div>
        )}
        
        {registerSuccess && (
          <div className="bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-200 p-3 rounded-md text-sm">
            注册成功！即将跳转到登录页面...
          </div>
        )}
        
        <form className="mt-8 space-y-6" onSubmit={handleSubmit(onSubmit)}>
          <div className="space-y-4">
            <div>
              <label htmlFor="username" className="label">
                用户名
              </label>
              <input
                id="username"
                name="username"
                type="text"
                autoComplete="username"
                className={`input ${errors.username ? 'border-red-500 dark:border-red-500' : ''}`}
                {...register('username', { 
                  required: '请输入用户名',
                  minLength: {
                    value: 3,
                    message: '用户名长度至少为3个字符'
                  },
                  maxLength: {
                    value: 20,
                    message: '用户名长度不超过20个字符'
                  },
                  pattern: {
                    value: /^[a-zA-Z0-9_]+$/,
                    message: '用户名只能包含字母、数字和下划线'
                  }
                })}
              />
              {errors.username && (
                <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                  {errors.username.message}
                </p>
              )}
            </div>
            
            <div>
              <label htmlFor="email" className="label">
                邮箱
              </label>
              <input
                id="email"
                name="email"
                type="email"
                autoComplete="email"
                className={`input ${errors.email ? 'border-red-500 dark:border-red-500' : ''}`}
                {...register('email', { 
                  required: '请输入邮箱',
                  pattern: {
                    value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
                    message: '请输入有效的邮箱地址'
                  }
                })}
              />
              {errors.email && (
                <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                  {errors.email.message}
                </p>
              )}
            </div>
            
            <div>
              <label htmlFor="password" className="label">
                密码
              </label>
              <input
                id="password"
                name="password"
                type="password"
                autoComplete="new-password"
                className={`input ${errors.password ? 'border-red-500 dark:border-red-500' : ''}`}
                {...register('password', { 
                  required: '请输入密码',
                  minLength: {
                    value: 6,
                    message: '密码长度至少为6个字符'
                  },
                  maxLength: {
                    value: 40,
                    message: '密码长度不超过40个字符'
                  }
                })}
              />
              {errors.password && (
                <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                  {errors.password.message}
                </p>
              )}
            </div>
            
            <div>
              <label htmlFor="confirmPassword" className="label">
                确认密码
              </label>
              <input
                id="confirmPassword"
                name="confirmPassword"
                type="password"
                autoComplete="new-password"
                className={`input ${errors.confirmPassword ? 'border-red-500 dark:border-red-500' : ''}`}
                {...register('confirmPassword', { 
                  required: '请确认密码',
                  validate: value => value === password || '两次输入的密码不一致'
                })}
              />
              {errors.confirmPassword && (
                <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                  {errors.confirmPassword.message}
                </p>
              )}
            </div>
          </div>
          
          <div className="flex items-center">
            <input
              id="agree-terms"
              name="agree-terms"
              type="checkbox"
              className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
              {...register('agreeTerms', { 
                required: '请同意服务条款和隐私政策'
              })}
            />
            <label htmlFor="agree-terms" className="ml-2 block text-sm text-dark-600 dark:text-dark-300">
              我已阅读并同意{' '}
              <Link to="/terms" className="text-primary-600 dark:text-primary-400 hover:underline">
                服务条款
              </Link>{' '}
              和{' '}
              <Link to="/privacy" className="text-primary-600 dark:text-primary-400 hover:underline">
                隐私政策
              </Link>
            </label>
          </div>
          {errors.agreeTerms && (
            <p className="mt-1 text-sm text-red-600 dark:text-red-400">
              {errors.agreeTerms.message}
            </p>
          )}
          
          <div>
            <button
              type="submit"
              disabled={isSubmitting || registerSuccess}
              className="btn btn-primary w-full flex justify-center items-center"
            >
              {isSubmitting ? (
                <span className="animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-white mr-2"></span>
              ) : null}
              注册
            </button>
          </div>
        </form>
        
        <div className="mt-6">
          <div className="relative">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-gray-300 dark:border-dark-600"></div>
            </div>
            <div className="relative flex justify-center text-sm">
              <span className="px-2 bg-white dark:bg-dark-800 text-gray-500 dark:text-gray-400">
                或通过以下方式注册
              </span>
            </div>
          </div>
          
          <div className="mt-6 grid grid-cols-2 gap-3">
            <div>
              <button
                type="button"
                className="w-full flex items-center justify-center btn bg-gray-100 dark:bg-dark-700 text-dark-700 dark:text-dark-300 hover:bg-gray-200 dark:hover:bg-dark-600"
              >
                <FaGithub className="w-5 h-5 mr-2" />
                <span>GitHub</span>
              </button>
            </div>
            
            <div>
              <button
                type="button"
                className="w-full flex items-center justify-center btn bg-gray-100 dark:bg-dark-700 text-dark-700 dark:text-dark-300 hover:bg-gray-200 dark:hover:bg-dark-600"
              >
                <FaGoogle className="w-5 h-5 mr-2" />
                <span>Google</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Register; 